import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import routes from './router'

Vue.use(Router)

var router = new Router({
  // mode : 'history',
  routes
})

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 页面刷新时，重新赋值token
if (window.localStorage.getItem('token')) {
  let userInfo = {
    identitytoken: window.localStorage.getItem('token'),
    userId: window.localStorage.getItem('userId'),
    userName: window.localStorage.getItem('userName')
  }
  store.commit('login', userInfo)
}

//前置守卫
router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.ignoreAuth)) {
    next();
  }else {
    if (store.state.token && store.state.isLogin) {
      next();
    }else if(to.path == "/register"){
      next();
    }else{
        next({
            path: '/login',
            query: {redirect: to.fullPath}
        })
    }
  }
})

export default router;
